"""
@author: yinjx
@file: bookcomment.py
@time: 2023/8/9 17:30
"""

from . import comment_bp


from models.user import Book
from flask import Blueprint, jsonify, request
from flask_restful import Api, Resource
from models.user import User,Book, Category,Comment
from models import db
import datetime
from models.user import BookCategory
from libs.response import generate_response
from libs.auth import auth_required
import json

api = Api(comment_bp)
class BookComments(Resource):
    # @auth_required
    def get(self, book_id):
        book = Book.query.get(book_id)
        if book:
            comments = Comment.query.filter_by(book_id=book_id).all()
            # 处理评论数据，将其转换为JSON格式
            comments_data = [{'content': comment.content, 'created_at': comment.created_at, 'username': comment.user.username} for comment in comments]
            return jsonify(comments=comments_data)
        else:
            return jsonify(error='Book not found'), 404

    # def post(self, book_id):
    #         # 获取当前登录用户的ID
    #         user_id = request.args.get('user_id')
    #
    #         # 获取评论内容
    #         content = request.json.get('content')
    #
    #         # 构建评论对象
    #         comment = Comment(content=content, created_at=datetime.now(), user_id=user_id, book_id=book_id)
    #
    #         # 将评论存储到数据库
    #         db.session.add(comment)
    #         db.session.commit()
    #
    #         return jsonify(message='评论添加成功')



api.add_resource(BookComments, "/book/<int:book_id>/comments", endpoint="book_comments")